#!/bin/bash -e
source reporting.sh

REPORT=/tmp/report.txt
CONFIG=/config/device/module_config.json

TEST_NAME='security.firmware'
TEST_DESCRIPTION='Automatic bacnet firmware scan using nmap'
TEST_SUMMARY=' Nothing more to report...'
LOG=/tmp/discover.log

# Error handling

if [ -f $CONFIG ]; then
    echo Extracting servers config from $CONFIG
    jq .servers $CONFIG
else
    echo No module config $CONFIG
fi

# Sanity

ping -n -c 3 $TARGET_IP

# Test command body

echo Running nmap 'bacnet_info' script

nmap --script bacnet-info -sU -p 47808 -oN $LOG $TARGET_IP

# Process the output of the test command
# Regex for capturing just the output, not the nmap lines with times/IPs:
# "PORT(.*\n)+MAC.*\n"
# or
# "(\|.*\n)+""

cat $LOG
touch $REPORT

rm -f .fail
OUTPUT=$(grep -Po "(?<=Firmware:\s).*" $LOG || true)
REDACTED_LOG=$(grep -Poz "PORT(.*\n)+MAC.*\n" $LOG || true)
TEST_SUMMARY=$(echo version found: $OUTPUT)

# pass/fail/info/skip logic

CONFIG_VERSION=`jq -r .device_info.firmware_version /config/device/module_config.json`
echo Version from config: $CONFIG_VERSION
echo Version from nmap: $OUTPUT

if [ -z $OUTPUT ]; then
    TEST_SUMMARY="Could not retrieve a firmware version with nmap. Check bacnet port."
    echo $TEST_SUMMARY
    result=skip
else
    if [ $CONFIG_VERSION == 'null' ]; then
        echo 'Firmware version not found in config'
        result=info
    else
        if [ "$CONFIG_VERSION" == "$OUTPUT" ]; then
            echo 'Firmware version matches config'
            result=pass
        else
            echo 'Firmware version is incorrect!'
            touch .fail
        fi
    fi
fi

if [ -f .fail ]; then
    echo Firmware version does not match...
    TEST_SUMMARY="$TEST_SUMMARY Firmware version does not match"
    echo "$REDACTED_LOG" 
    result=fail
else
    echo "$REDACTED_LOG \nFirmware test complete" 
    echo 'Firmware test complete' 
fi

# Show 'done' rather than an error state for everything except 'fail'

RESULT_AND_SUMMARY="RESULT $result $TEST_NAME $TEST_SUMMARY"

write_out_result $REPORT \
                 "$TEST_NAME" \
                 "$TEST_DESCRIPTION" \
                 "$REDACTED_LOG" \
                 "$RESULT_AND_SUMMARY"

